package com.aw.baselib.net

import okhttp3.MediaType
import okhttp3.RequestBody

/**
 * Created by hzw
 */
object FormDataConvertUtil {
    /**
     * 转换为 form-data
     *
     * @param requestDataMap
     * @return
     */
    fun generateRequestBody(requestDataMap: Map<String, String?>): Map<String, RequestBody> {
        val requestBodyMap: MutableMap<String, RequestBody> = HashMap()
        for (key in requestDataMap.keys) {
            val requestBody = RequestBody.create(
                MediaType.parse("multipart/form-data"),
                if (requestDataMap[key] == null) "" else requestDataMap[key]
            )
            requestBodyMap[key] = requestBody
        }
        return requestBodyMap
    }

    fun getRequestBody(hashMap: HashMap<String?, String?>?): RequestBody {
        val data = StringBuffer()
        if (hashMap != null && hashMap.size > 0) {
            val iter: Iterator<*> = hashMap.entries.iterator()
            while (iter.hasNext()) {
                val (key1, value) = iter.next() as Map.Entry<*, *>
                val key = key1!!
                val `val` = value!!
                data.append(key).append("=").append(`val`).append("&")
            }
        }
        val jso = data.substring(0, data.length - 1)
        return RequestBody.create(
            MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),
            jso
        )
    }
}